import api from "@/utils/api";
import globalModelStore from "@/utils/static";
import { message } from "antd";
import axios from "axios";


//设置请求间隔时间
let time: any = {
  start: 0,
  end: 0,
};

//=======================================
axios.defaults.timeout = 8000; // 默认的超时时间
axios.defaults.withCredentials = true; // 表示跨域请求时是否需要使用凭证

/**
 * 正在进行（pending 状态）的请求记录
 */
// 记录所有正在进行（pending 状态）的请求的 "唯一值" 和 "取消请求方法"
const allPendingRequestsRecord = [];
/**
 * 通过请求的 url 和 method 来标示请求唯一值
 * @param {*} config 配置信息
 * @returns
 */
function getUniqueId(config) {
  return `url=${config.url}&method=${config.method}`;
}
/**
 * 取消请求，并移除记录
 * @param {*} config 配置信息
 */
function removePendingRequestRecord(config) {
  allPendingRequestsRecord.some((item, index) => {
    if (item.id === getUniqueId(config)) {
      // console.log('-- cancel id:', item.id)
      item.cancel(); // 取消请求
      allPendingRequestsRecord.splice(index, 1); // 移除记录
      return true;
    }
  });
  // console.log('-- allPendingRequestsRecord:', allPendingRequestsRecord.length, JSON.stringify(allPendingRequestsRecord))
}
/**
 * 取消所有请求并移除所有记录
 *
 * 页面切换时，取消所有请求并移除所有记录 useAge:
 *    import {removeAllPendingRequestsRecord} from './helper/axios';
 *    router.beforeEach((to, from, next) => {
 *      removeAllPendingRequestsRecord();
 *    }
 */
export function removeAllPendingRequestsRecord() {
  allPendingRequestsRecord.forEach((item) => {
    item.cancel("page changes"); // 取消请求
  });
  allPendingRequestsRecord.splice(0); // 移除所有记录
}
//=======================================
axios.defaults.timeout = 30000;//设置超时的时间

//发送请求之前做些什么
axios.interceptors.request.use(
  function (config: any) {
    //time.start = new Date().valueOf();
    // 在 get 请求上带上时间戳

    //const connec=config.url.search(/\?/) === -1?'?':'&';

    /* //判断是?还是&
    if (config.method === "get") {
      config.url = config.url + connec + new Date().getTime();
    } */
    // 通过添加随机 uniqueCancel 值，确保每个请求具有唯一标示
    //config.url = `${config.url}${connec}uniqueCancel=${Math.random().toString(36).substr(2)}`;

    // 在请求发送前执行一下取消操作，防止重复发送请求（dashboard 类似页面具有重复多次的相同请求，所有不能在全局做防止重复）
    // removePendingRequestRecord(config)


    // 设置请求的 cancelToken
    config.cancelToken = new axios.CancelToken(function executor(cancel) {
      // 添加记录，记录请求的唯一值和取消方法
      allPendingRequestsRecord.push({ id: getUniqueId(config), cancel });
    });
    //console.log('-- request config:', config)
    if (config.url.includes(api.histreatmentRecord)) {
      config.headers.Accept = "*/*";
      config.responseType="blob";
      return config;
      return;
    }
    if (
      config.url.includes(api.hardwaretreatmentRecord) ||
      config.url.includes(api.getCureRecordTemplate) ||
      config.url.includes(api.zlapi_curerecorddownload) ||
      config.url.includes(api.zlapi_smCureRecordDownload) ||
      config.url.includes(api.fingerprintFile)
    ) {
      console.log("===>98===>",config);
      config.headers.Accept = "*/*";
      config.responseType="blob";
      let token = JSON.parse(localStorage.getItem("device"))?.token
      config.headers.Authorization = token ? token : "";
      return config;
      return;
    }
    if (config.url.includes(api.loginByWeb)||config.url.includes(api.getTmsCureRecordToHis)) {

      config.headers.post["Content-Type"] = "application/json";
      //config.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    }else if(config.url.includes('isfile=true')){
      config.headers.Accept = "*/*";
      config.responseType="blob";
      let token = JSON.parse(localStorage.getItem("device"))?.token
      config.headers.Authorization = token ? token : "";

    } else {
      //config.headers["Access-Control-Allow-Origin"]="http://192.168.0.220";
      //config.headers["Access-Control-Allow-Credentials"]="true";
      config.headers.post["Content-Type"] = "application/json";
      //config.headers.put['Content-Type'] = 'application/json';
      // config.headers.Authorization = globalModelStore.token;
      let token = JSON.parse(localStorage.getItem("device"))?.token
      config.headers.Authorization = token ? token : "";
    }



    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

const blobToString=(blobdata)=>{
  return new Promise((resolve, reject) => {
    try{
      let reader = new FileReader();
      reader.onload = function(event){
        resolve(reader.result);
      };
      reader.readAsText(blobdata);
    }catch (e){
      reject(e);
    }
  });
}

// 添加响应拦截器
axios.interceptors.response.use(
  async function (response) {
    time.end = new Date().valueOf();

    //重新设置返回的数据结构,方便使用
    const ct=response.headers["content-type"];
    if (ct&& ct.indexOf("application/json") != -1 ) {
      if(response.request.responseType=="blob"){
        const blobdata=await blobToString(response.data);
        response.data=JSON.parse(blobdata.toString())
        response.data.ts = response.status;
        (response.data.time = (time.end - time.start) / 1000),
          (response.data.to = {
            responseText: blobdata,
            url: response.config.url,
            data: response.config.data,
            params: response.config.params,
            method: response.config.method,
            content_type: response.config.headers["Content-Type"],
            Authorization: response.config.headers.Authorization,
          });
        //在一个请求响应后再执行一下取消操作，把已经完成的请求从pending中移除
        removePendingRequestRecord(response.config);
        return response.data;
      }else{
        response.data.ts = response.status;
        (response.data.time = (time.end - time.start) / 1000),
          (response.data.to = {
            responseText: response.request.responseText,
            url: response.config.url,
            data: response.config.data,
            params: response.config.params,
            method: response.config.method,
            content_type: response.config.headers["Content-Type"],
            Authorization: response.config.headers.Authorization,
          });
        //在一个请求响应后再执行一下取消操作，把已经完成的请求从pending中移除
        removePendingRequestRecord(response.config);
        return response.data;
      }
    }else{
      //非json数据直接返回全部
      removePendingRequestRecord(response.config);
      return response;
    }
  },
  function (error) {
    console.log("===超时===>",error);
    message.info("连接超时")
    if (error && error.response) {
      //check(error.response.data);
      return error.response.data;
    }
    // 请求配置发生的错误
    /*if (error && error.response) {
       // 获取状态码
      const status = error.response.status;
      const errortext = codeMessage[status] || error.response.statusText;

      // 错误状态处理
      if (status === 401) {
        router.push('/login')
      } else if (status === 403) {
        router.push('/login')
      } else if (status >= 404 && status < 422) {
        router.push('/404')
      }
      console.log('====error====',error.response)
      return {
        ts: error.response.status,
        message: error.message,
      };
    }
    console.log('====error====',error.response)*/
    /* return {
      ts: error.response.status,
      message: error.message,
    }; */
    /*

    console.log('=errormessage=', error.message);
    console.log('=errorconfig=', error.config);
    console.log('=errorrequest=', error.request);
    return error.message;//Promise.reject(error); */
  }
);

// 封装axios
function apiAxios(method: string, url: string, params?: any, options = {}) {
  if (method === "GET" || method === "DELETE") {
    if (params) {
      let paramsArray = [];
      //拼接参数
      Object.keys(params).map((item,index) =>
        paramsArray.push(item + "=" + params[item])
      );
      //如果没有参数就不添加?
      if (paramsArray.length > 0) {
        if (url.search(/\?/) === -1) {
          url += "?" + paramsArray.join("&");
        } else {
          url += "&" + paramsArray.join("&");
        }
      }
    }
  }

  /* let httpDefault = {
    method: method,
    url: url,
    params: !(method === 'POST' || method === 'PUT') ? JSON.stringify(params) : null,
    data: method === 'POST' || method === 'PUT' ? JSON.stringify(params) : null,
    ...options,
  }; */

  let httpDefault;
  if (method === "POST" || method === "PUT") {
    httpDefault = {
      method: method,
      url: url,
      data: params,
      //params: params,
    };
  } else {
    httpDefault = {
      method: method,
      url: url,
      //params: JSON.stringify(params),
    };
  }
  httpDefault = { ...httpDefault, ...options,};

  return new Promise((resolve, reject) => {
    axios(httpDefault)
      .then((res) => {
        resolve(res);
      })
      .catch((error) => {
        console.log("error", error);
        reject(error);
      });
  });
}

export default apiAxios;
